﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Requests;
using MethodWorx.CMS.Services;
using MethodWorx.Core.Validation;

namespace MethodWorx.CMS.TemplateParser.Installer.Components
{
    public class Page : IInstallationWorkflowComponent, IValidationProvider
    {
        public Workflow.StepExecutionResult Execute(Workflow.IWorkflowExecutionContext context, InstallerWorkflowComponentConfiguration configuration)
        {
            using (var uow = context.CmsDataProvider.GetUnitOfWorkFactory().Begin())
            {
                
                //  get the variables from the workflow context, used to parse out the information
                //  in the template
                var variables = context.GetAllWorkflowValues();
                //  get the content service to create the page
                var contentService = new ContentService(context.CmsDataProvider);
                //  get the schema service to lookup the template
                var schemaService = new SchemaService(context.CmsDataProvider);
                //  get the template name from the step configuration (parsing the names with any workflow variables)
                var templateName = configuration.ConfigurationElement.GetAttributeValue("template", null, true, context.GetAllWorkflowValues());
                var name = configuration.ConfigurationElement.GetAttributeValue("name", null, true, context.GetAllWorkflowValues());
                var parentId = Guid.Parse(configuration.ConfigurationElement.GetAttributeValue("parent", null, true, context.GetAllWorkflowValues()));

                var parent = contentService.GetPageById(parentId);
                var template = schemaService.GetPageTemplateByName(templateName);


                if(string.IsNullOrEmpty(templateName))
                    throw new Exception("Please enter a template name");

                if(string.IsNullOrEmpty(name))
                    throw new Exception("Please enter a page name");


                var output = contentService.CreatePage(new CreatePageRequest(parent, context.CurrentUser)
                                       {
                                           ExistingPageTemplate = template,
                                           PageName = name
                                       }, this);
                

                uow.Commit();

                return Workflow.StepExecutionResult.Ok(output.Id);
            }
            
        }

        public bool Validate(object instance)
        {
            return true;
        }

        public void AddError(string key, string message)
        {
            throw new Exception(message);
        }

        public bool IsValid()
        {
            return true;
        }
    }
}
